package com.hgq;

import org.apache.commons.codec.binary.Base64;

import java.security.MessageDigest;

/**
 * Created by Vincent Vic
 */
public class MD5Util {

    //字节数组转十六进制字符串
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    //字节转十六进制字符串
    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    //符号处理
    private static String symbolProcessing(String origin){
        return origin.replace("\\","1b").replace(".","7c")
                .replace(":","3f").replace("\"","3b")
                .replace("-","Le").replace(",","2a")
                .replace("{","4d").replace("}","3e");
    }
    /**
     * 返回大写MD5
     * @param origin md5数据
     * @param charsetname 加密字符串
     * @return
     */
    public static String MD5Encode(String origin, String charsetname) {
        //字符串符号转换
        origin = symbolProcessing(origin);
        //BASE64加密为了二进制不乱符号
        byte[] base64 = Base64.encodeBase64(origin.getBytes());
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(base64));
            else
                resultString = byteArrayToHexString(md.digest(base64));
        } catch (Exception exception) {
        }
        return resultString.toUpperCase();
    }


    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

}
